//
//  BYNetworkActivityPlugin.swift
//  Merchants
//
//  Created by kingly09 on 2020/7/14.
//  Copyright © 2020 kingly09. All rights reserved.
//

import UIKit
import Moya

class BYNetworkActivityPlugin: PluginType {
    public func willSend(_ request: RequestType, target: TargetType) {
        
        let netRequest = request.request
        
        if let url = netRequest?.description {
            
            print("✅ " + url)
        }
        if let httpMethod = netRequest?.httpMethod {
            print("METHOD:\(httpMethod)")
        }
        
        if let body = netRequest?.httpBody, let output = String(data: body, encoding: .utf8) {
            
            print("Body:\(output)")
        }
    }
    
    public func didReceive(_ result: Result<Response, MoyaError>, target: TargetType) {
        
        switch result {
        case .success(let moyaResponse):
            print("")
            let data =  moyaResponse.data
            let dict = JSONResponseFormatter(data)
//            print("respose ：\(dict ?? [:]) ")
        case .failure(let error):
            print("❌ \(error.errorDescription ?? "无错误描述")")
        }
    }
    
    
    //json解析
    private func JSONResponseFormatter(_ data: Data) -> NSDictionary? {
        do {
            let dataAsJSON = try JSONSerialization.jsonObject(with: data)
            
            return dataAsJSON as? NSDictionary
        } catch {
            return nil
        }
    }
}

public extension URL{
    init<T: TargetType>(t target: T) {
        if target.path.isEmpty {
            self = target.baseURL
        }else {
            self = target.baseURL.appendingPathComponent(target.path)
        }
    }
}

public extension MoyaProvider {
    final class func customEndpointMapping(for target: Target) -> Endpoint {

       return Endpoint(
           url: URL(t: target).absoluteString,
           sampleResponseClosure: { .networkResponse(200, target.sampleData) },
           method: target.method,
           task: target.task,
           httpHeaderFields: target.headers
       )
   }
}

